MT.requireFile("js/qrcode.min.js");

MT.extend("core.Emitter").extend("core.BasicPlugin")(
	MT.plugins.Export = function(project){
		MT.core.BasicPlugin.call(this, "Export");
		this.project = project;
	},
	{
		get path(){
			return "data/build/" + this.project.id + "/" + this.project.data.rev;
		},
		
		initUI: function(ui){
			var that = this;
			this.list = new MT.ui.List([
				{
					label: "Phaser.io (.js)",
					title: "Phaser.io Project",
					className: "",
					cb: function () {
						var not = that.project.plugins.notification.show("Exporting project...", that.project.data.title);
						that.export("phaser", {
							zip: 1
						},
						function (data) {
							window.location = that.path + "/" + data.file;
							not.hide();
						});
					}
				},
				{
                    label: "Web App (Phaser.io minified)",
					title: "Minified project sources based on Phaser.io framework",
                    className: "",
                    cb: function () {
						that.minify();
                    }
				},
				{
					label: "Android",
					contents: [
						{
							label: "Crosswalk",
							contents: [
								{
									label: "Debug (ARM)",
									title: "most android phones uses arm processors",
									className: "",
									cb: function () {
										that.crosswalk("arm");
									}
								},
								{
									label: "Debug (x86)",
									title: "some phones and tablets uses intel atom or similar cpus",
									className: "",
									cb: function () {
										that.crosswalk("x86");
									}
								},
								{
									label: "Release (ARM)",
									title: "most android phones uses arm processors",
									className: "",
									cb: function () {
										that.crosswalk("arm", true);
									}
								},
								{
									label: "Release (x86)",
									title: "some phones and tablets uses intel atom or similar cpus",
									className: "",
									cb: function () {
										that.crosswalk("x86", true);
									}
								}
							]
						},
						{
							label: "Cordova",
							contents: [
								{
									label: "Debug",
									cb: function () {
										that.cordova();
									}
								},
								{
									label: "Release",
									cb: function () {
										that.cordova(1);
									}
								}
							]
						}
					]
				},
				
				{
					label: "data only - js",
					title: "data generated by editor - javascript format",
					className: "",
					cb: function () {
						that.export("phaserDataOnly", function (data) {
							that.openDataLink(data, "js");
						});
					}
				},
				{
					label: "data only - json",
					title: "data generated by editor - JSON format",
					className: "",
					cb: function () {
						that.export("phaserDataOnly", function (data) {
							that.openDataLink(data, "json");
						});
					}
				}
				], ui, true);

			var b = this.button= this.project.panel.addButton("Export", null, function(e){
				that.showList();
			});
			var om = this.project.plugins.objectmanager;

			this.openGame = this.project.panel.addButton("Open Game", null, function(e){
				om.sync();
				that.openLink("_open_game");
			});
		},

		export: function(dest, data, cb){
			if(typeof data == "function"){
				cb = data;
				data = null;
			}
			this.send(dest, data, cb);
		},

		showList: function(){
			this.list.width = 250;
			this.list.y = this.button.el.offsetHeight;
			this.list.x = this.button.el.offsetLeft-5;
			this.list.el.style.bottom = "initial";
			this.list.show(document.body);
		},

		openDataLink: function(data, json){
			if(json == "json"){
				data.file += "on";
			}
			var w = window.innerWidth*0.5;
			var h = window.innerHeight*0.8;
			var l = (window.innerWidth - w)*0.5;
			var t = (window.innerHeight - h)*0.5;

			window.open(this.path + "/" + data.file,"","width="+w+",height="+h+",left="+l+",top="+t+"");
		},

		openLink: function(name){
			var w = window.open("about:blank",name || Date.now());
			w.focus();
			//w.opener = null;

			var path = this.path;
			this.export("phaser", {
				zip: 0
			},
			function(data){
				if(w.location){
					w.location.href = path + "/" +data.name + "/index.html";
					w.focus();
				}
			});
		},
		
		popWithDots: function(label){
			var dots = "...";
			
			var pop = new MT.ui.Popup("Export", label + dots);
			
			pop.y = 150;
			var interval = window.setInterval(function(){
				dots += ".";
				if(dots.length > 3){
					dots = "";
				}
				pop.content.innerHTML = label + dots;
			}, 300);
			
			pop.clear = function(){
				window.clearInterval(interval);
			};
			
			return pop;
		},
		
		crosswalk: function(arch, release){
			var that = this;
			
			if( !this.project.data.package ){
				this.project.updateProject(function(props){
					that.crosswalk(arch, release);
				});
				return;
			}
			
			var pop = this.popWithDots("Building apk");
			that.export("crosswalk", {arch: arch, rel: release}, function (data) {
				pop.clear();
				
				if(data.requireProLevel){
					pop.showClose();
					pop.content.innerHTML = "Only subscribers can use this feature!";
					pop.addButton("OK", function(){pop.hide();});
					return;
				}
				
				if(data.requireSignature){
					pop.hide();
					that.genKeystoreForm(function(){
						that.crosswalk(arch, release);
					});
					return;
				}
				
				if(data.requirePackage){
					pop.hide();
					that.project.updateProject(function(props){
						that.crosswalk(arch, release);
					});
					return;
				}
				
				pop.showClose();
				pop.addButton("Done", function(){pop.hide();});
				
				if(data.serr && data.serr.length){
					pop.content.innerHTML = "Please review errors and try again!<br />";
					var list = '<ul class="error-list">';
					for(var i=0; i<data.serr.length; i++){
						list += "<li>"+data.serr[i].trim()+"</li>";
					}
					pop.content.innerHTML += list + "</ul>";
					
				}
				else{
					pop.content.innerHTML = "DONE!";
					that.linkWithQR(pop.content, "Download", data.link);
				}
			});
		},
		
		cordova: function(release){
			if( !this.project.data.package ){
				this.project.updateProject(function(props){
					that.cordova();
				});
				return;
			}
			
			var that = this;
			var pop = this.popWithDots("Building apk");
			that.export("cordova", {rel: release}, function (data) {
				pop.clear();
				pop.showClose();
				
				if(data.requireProLevel){
					pop.content.innerHTML = "Only subscribers can use this feature!";
					pop.addButton("OK", function(){pop.hide();});
					return;
				}
				
				pop.showClose();
				pop.addButton("Done", function(){pop.hide();});
				if(data.serr && data.serr.length){
					pop.content.innerHTML = "Please review errors and try again!<br />";
					var list = '<ul class="error-list">';
					for(var i=0; i<data.serr.length; i++){
						list += "<li>"+data.serr[i].trim()+"</li>";
					}
					pop.content.innerHTML += list + "</ul>";
					
				}
				else{
					pop.content.innerHTML = "DONE!";
					that.linkWithQR(pop.content, "Download", data.link);
				}
			});
		},
		cordovaProject: function(){
			
		},
		genKeystoreForm: function(cb){
			var that = this;
			
			var info = {
				CN: "John Smith",
				OU: "Mobile Games", 
				O: "My Company", 
				L: "My Town",
				ST: "My State",
				C: "UN"
			};
			
			var names = {
				CN: "First and Last Name (CN)",
				OU: "Organizational Unit (OU)", 
				O: "Organization (O)", 
				L: "City or Location (L)",
				ST: "State or Province (ST)",
				C: "Country Code (XX) (C)"
			};
			
			var pop = new MT.ui.Popup("Keystore", "");
			pop.showClose();
			var input;
			for(var i in info){
				input = new MT.ui.Input(this.project.ui, {key: i, label: names[i], type: "text"}, info, function(n,o){
					//console.log("xxx", n, o);
				});
				input.show(pop.content);
			}
			pop.show();
			
			pop.addButton("Next", function(){
				pop.hide();
				that.send("genKeystore", info, function(error){
					if(error){
						console.error(error);
						return;
					}
					if(cb){
						cb();
					}
				});
				
			});
		},
		
		linkWithQR: function(parent, label, link){
			var div = document.createElement("div");
			div.className = "table";
			
			var a = document.createElement("a");
			a.style.width = "90px";
			a.setAttribute("target", "_blank");
			a.setAttribute("href", link);
			a.appendChild(document.createTextNode(label));
			
			var input = document.createElement("input");
			input.value = link;
			input.style.cssText = "padding: 3px; width: 100%";
			
			var qr = document.createElement("div");
			var qrcode = new QRCode(qr, {
				text: link,
				width: 256,
				height: 256,
				colorDark : "#000000",
				colorLight : "#ffffff",
				correctLevel : QRCode.CorrectLevel.H
			});
			
			div.appendChild(a);
			div.appendChild(input);
			
			parent.appendChild(div);
			parent.appendChild(qr);
		},
		
		
		minify: function(){
			var that = this;
			var label = "Export in progress";
			
			
			var pop = this.popWithDots(label);
			
			
			this.export("phaserMinify", function (data) {
				pop.clear();
				
				pop.showClose();
				pop.addButton("Done", function(){pop.hide();});
				
				var base = window.location.origin + "/" + that.path + "/" + data.file;
				
				var link1 = base + "-minified/index.html";
				var link2 = base + '.min.zip';
				
				pop.content.innerHTML = '<div class="table">'+
					'<a href="' + link1 + '" style="width: 90px" target="_blank">Open</a><input value="'+link1+'"  style="padding: 3px; width: 100%" /></div><div id="link1"></div>';
				pop.content.innerHTML += '<div class="table">'+
					'<a href="' + link2 + '" style="width: 90px" target="_blank">Download</a><input value="'+link2+'"  style="padding: 3px; width: 100%" /></div><div id="link2"></div>';
				
				var x = document.getElementById("link1");
				var qrcode = new QRCode(x, {
					text: link1,
					width: 256,
					height: 256,
					colorDark : "#000000",
					colorLight : "#ffffff",
					correctLevel : QRCode.CorrectLevel.H
				});
				
				var img1 = x.lastChild;
				img1.style.cursor = "pointer";
				img1.width = 32;
				img1.height = 32;
				img1.onmouseup = function(e){
					if(this.width < 256){
						this.width = 256;
						this.height = 256;
						
						img2.width = 32;
						img2.height = 32;
					}
					else{
						this.width = 32;
						this.height = 32;
						
						img2.width = 256;
						img2.height = 256;
					}
				};
				
				
				x = document.getElementById("link2");
				qrcode = new QRCode(x, {
					text: link2,
					width: 256,
					height: 256,
					colorDark : "#000000",
					colorLight : "#ffffff",
					correctLevel : QRCode.CorrectLevel.H
				});
				
				var img2 = x.lastChild;
				img2.style.cursor = "pointer";
				//img2.width = 32;
				//img2.height = 32;
				img2.onmouseup = function(e){
					if(this.width < 256){
						this.width = 256;
						this.height = 256;
						
						img1.width = 32;
						img1.height = 32;
					}
					else{
						this.width = 32;
						this.height = 32;
						
						img1.width = 256;
						img1.height = 256;
						
					}
				};
				
			});
		},
		
		a_complete: function(data){
			this.emit("done", data);
		}

	}
);
